package cn.com.doone.common.uc.utils;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.SearchResult;


public class LdapUtils {

	
	
	/**
	 * Converts an generalized times to a java.util.Timestamp object
	 * @param s timestamp string from OpenLDAP 
	 * @return t
	 */
	public static Timestamp generalized2timestamp(String s, TimeZone tz) {
		s = s.substring(0, 14); // remove the ending char 'Z';
	
		Timestamp t = null;
		SimpleDateFormat mySimpleFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	
		try {
			t = new Timestamp(mySimpleFormat.parse(s).getTime());
		} catch (Exception e) {
		}
	
		return t;
	}

	/**
	 * Converts a java.util.Timestamp to a generalized time
	 * @param mytime input timestamp
	 * @return localized timestamp ?
	 */
	public static String Timestamp2generalized(Timestamp mytime, TimeZone tz) {
		Timestamp b = new Timestamp(mytime.getTime());
		SimpleDateFormat mySimpleFormat = new SimpleDateFormat("yyyyMMddHHmmssZ");
		mySimpleFormat.setTimeZone(tz);
	
		return mySimpleFormat.format(b);
	}

	/**
	 * Converts a java.util.Timestamp to UTC
	 * needed if the "Generalized Time Syntax Plug-in" of FedoraDS is not enabled
	 * @param mytime input timestamp
	 * @return UTC SQL timestamp
	 */
	public static String Timestamp2UTC(Timestamp mytime) {
		Timestamp b = new Timestamp(mytime.getTime());
		SimpleDateFormat mySimpleFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		mySimpleFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
		String ret = mySimpleFormat.format(b) + "Z";
	
		return ret;
	}

	public static String getPrintableAttribute(Attribute p) {
		String ret = null;
		try {
			if (p != null) {
				ret = (String) p.get();
			} 
		} catch (NamingException e) {
			//noop
		}
		return ret != null ? ret : "";
	}

	public static String getPrettyAttribute(SearchResult sr, String attributeName) throws NamingException {
		String ret = null;
		if ( (attributeName != null) && (sr != null)) {
			Attribute attr  = sr.getAttributes().get(attributeName);
			if (attr != null) {
				ret =  (String) attr.get();
			}
		}
		return (ret != null) ? ret : ""; 
	}


}